<!-- 算法练习页面 -->
<template>
  <div class="algorithm-practice">
    <el-row :gutter="20">
      <!-- 左侧章节和题目列表 -->
      <el-col :span="8">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>算法章节</span>
          </div>
          
          <!-- 章节选择 -->
          <el-select 
            v-model="selectedChapter" 
            placeholder="请选择算法章节"
            @change="onChapterChange"
            style="width: 100%; margin-bottom: 20px;"
          >
            <el-option
              v-for="chapter in chapters"
              :key="chapter.id"
              :label="chapter.title"
              :value="chapter.id"
            >
            </el-option>
          </el-select>

          <!-- 题目列表 -->
          <div v-if="quizList.length > 0">
            <div 
              v-for="quiz in quizList" 
              :key="quiz.id"
              class="quiz-item"
              :class="{ active: selectedQuiz && selectedQuiz.id === quiz.id }"
              @click="selectQuiz(quiz)"
            >
              <div class="quiz-title">{{ quiz.title }}</div>
              <div class="quiz-difficulty">
                <el-tag 
                  :type="getDifficultyType(quiz.difficulty)" 
                  size="mini"
                >
                  {{ getDifficultyText(quiz.difficulty) }}
                </el-tag>
              </div>
            </div>
          </div>
          <div v-else class="no-quiz">
            该章节暂无题目
          </div>
        </el-card>
      </el-col>

      <!-- 右侧题目详情和代码编辑 -->
      <el-col :span="16">
        <el-card class="box-card" v-if="selectedQuiz">
          <div slot="header" class="clearfix">
            <span>{{ selectedQuiz.title }}</span>
            <el-button 
              style="float: right; padding: 3px 0" 
              type="text"
              @click="showSaveDialog = true"
            >
              保存代码
            </el-button>
            <el-button 
              style="float: right; padding: 3px 0; margin-right: 10px;" 
              type="text"
              @click="showLoadDialog = true"
            >
              加载代码
            </el-button>
          </div>

          <!-- 题目描述 -->
          <div class="quiz-description">
            <h3>题目描述</h3>
            <p>{{ selectedQuiz.description }}</p>
            
            <h3>函数签名</h3>
            <pre class="function-signature">{{ selectedQuiz.functionSignature }}</pre>
            
            <h3>要求</h3>
            <ul>
              <li>时间限制：{{ selectedQuiz.timeLimit }}ms</li>
              <li>内存限制：{{ selectedQuiz.memoryLimit }}MB</li>
            </ul>
          </div>

          <!-- 代码编辑器 -->
          <div class="code-editor">
            <h3>代码编辑</h3>
            <div class="editor-container">
              <textarea
                v-model="code"
                class="code-textarea"
                placeholder="请在此输入您的代码..."
                @input="onCodeChange"
              ></textarea>
            </div>
            <div class="editor-actions" style="display: flex; align-items: center; justify-content: flex-end; gap: 10px;">
              <el-select v-model="pythonVersion" placeholder="选择Python版本" style="width: 120px;">
                <el-option label="Python2" value="python2" />
                <el-option label="Python3" value="python3" />
              </el-select>
              <el-button type="success" @click="runCode">运行代码</el-button>
              <el-button type="primary" @click="submitCode" :loading="submitting">提交代码</el-button>
              <el-button @click="resetCode">重置代码</el-button>
            </div>
          </div>

          <!-- 运行结果展示 -->
          <el-card v-if="runResult" class="box-card" style="margin-top: 20px;">
            <div slot="header">运行结果</div>
            <pre style="white-space: pre-wrap;">{{ runResult }}</pre>
          </el-card>

          <!-- 提交结果 -->
          <div v-if="submitResult" class="submit-result">
            <h3>提交结果</h3>
            <el-alert
              :title="getResultTitle()"
              :type="getResultType()"
              :description="getResultDescription()"
              show-icon
              :closable="false"
            >
            </el-alert>
            
            <!-- 测试用例结果 -->
            <div v-if="submitResult.testCaseResults && submitResult.testCaseResults.length > 0" class="test-case-results">
              <h4>测试用例详情</h4>
              <el-table :data="submitResult.testCaseResults" size="small">
                <el-table-column prop="testCaseId" label="用例ID" width="80"></el-table-column>
                <el-table-column prop="inputData" label="输入" width="150"></el-table-column>
                <el-table-column prop="expectedOutput" label="期望输出" width="150"></el-table-column>
                <el-table-column prop="actualOutput" label="实际输出" width="150"></el-table-column>
                <el-table-column prop="executionTime" label="执行时间(ms)" width="100"></el-table-column>
                <el-table-column label="状态" width="80">
                  <template slot-scope="scope">
                    <el-tag :type="scope.row.passed ? 'success' : 'danger'" size="mini">
                      {{ scope.row.passed ? '通过' : '失败' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="errorMessage" label="错误信息"></el-table-column>
              </el-table>
            </div>
          </div>
        </el-card>

        <el-card v-else class="box-card">
          <div class="no-selection">
            请选择左侧的题目开始练习
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 保存代码对话框 -->
    <el-dialog title="保存代码" :visible.sync="showSaveDialog" width="400px">
      <el-form :model="saveForm" label-width="80px">
        <el-form-item label="代码名称">
          <el-input v-model="saveForm.codeName" placeholder="请输入代码名称"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showSaveDialog = false">取消</el-button>
        <el-button type="primary" @click="saveCode">保存</el-button>
      </div>
    </el-dialog>

    <!-- 加载代码对话框 -->
    <el-dialog title="加载代码" :visible.sync="showLoadDialog" width="500px">
      <div v-if="savedCodes.length > 0">
        <div 
          v-for="code in savedCodes" 
          :key="code.id"
          class="saved-code-item"
          @click="loadCode(code)"
        >
          <div class="code-name">{{ code.codeName }}</div>
          <div class="code-time">{{ formatTime(code.saveTime) }}</div>
        </div>
      </div>
      <div v-else class="no-saved-codes">
        暂无保存的代码
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'AlgorithmPractice',
  data() {
    return {
      // 章节相关
      chapters: [],
      selectedChapter: null,
      
      // 题目相关
      quizList: [],
      selectedQuiz: null,
      
      // 代码相关
      code: '',
      submitting: false,
      submitResult: null,
      
      // 对话框相关
      showSaveDialog: false,
      showLoadDialog: false,
      saveForm: {
        codeName: ''
      },
      savedCodes: [],
      pythonVersion: 'python3',
      runResult: ''
    }
  },
  
  created() {
    this.fetchChapters()
  },
  
  methods: {
    // 获取章节列表
    fetchChapters() {
      this.$http({
        url: this.$http.adornUrl('/practice/algorithm/chapters'),
        method: 'get',
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.chapters = data.data || []
          if (this.chapters.length > 0) {
            this.selectedChapter = this.chapters[0].id
            this.onChapterChange()
          }
        }
      })
    },
    
    // 章节切换
    onChapterChange() {
      this.selectedQuiz = null
      this.code = ''
      this.submitResult = null
      this.fetchQuizList()
    },
    
    // 获取题目列表
    fetchQuizList() {
      if (!this.selectedChapter) return
      this.$http({
        url: this.$http.adornUrl('/practice/algorithm/quiz/list'),
        method: 'get',
        params: this.$http.adornParams({ chapterId: this.selectedChapter }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.quizList = data.data || []
        }
      })
    },
    
    // 选择题目
    selectQuiz(quiz) {
      this.selectedQuiz = quiz
      this.code = ''
      this.submitResult = null
      this.fetchQuizDetail(quiz.id)
      this.fetchSavedCodes(quiz.id)
    },
    
    // 获取题目详情
    fetchQuizDetail(quizId) {
      this.$http({
        url: this.$http.adornUrl(`/practice/algorithm/quiz/${quizId}`),
        method: 'get',
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.selectedQuiz = data.data
        }
      })
    },
    
    // 提交代码
    submitCode() {
      if (!this.selectedQuiz || !this.code) {
        this.$message.warning('请选择题目并输入代码')
        return
      }
      
      this.submitting = true
      this.$http({
        url: this.$http.adornUrl('/practice/algorithm/submit'),
        method: 'post',
        data: this.$http.adornData({
          quizId: this.selectedQuiz.id,
          code: this.code,
          language: 'python',
        }, false),
      }).then(({ data }) => {
        this.submitting = false
        if (data && data.code === 0) {
          this.submitResult = data.data
        } else {
          this.$message.error(data.msg || '提交失败')
        }
      }).catch(() => {
        this.submitting = false
      })
    },
    
    // 重置代码
    resetCode() {
      this.code = ''
      this.submitResult = null
    },
    
    // 保存代码
    saveCode() {
      if (!this.selectedQuiz || !this.code || !this.saveForm.codeName) {
        this.$message.warning('请填写代码名称并输入代码')
        return
      }
      this.$http({
        url: this.$http.adornUrl('/practice/algorithm/save-code'),
        method: 'post',
        data: this.$http.adornData({
          quizId: this.selectedQuiz.id,
          codeName: this.saveForm.codeName,
          codeContent: this.code,
          language: 'python',
        }, false),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message.success('保存成功')
          this.showSaveDialog = false
          this.fetchSavedCodes(this.selectedQuiz.id)
        } else {
          this.$message.error(data.msg || '保存失败')
        }
      })
    },
    
    // 加载代码列表
    fetchSavedCodes(quizId) {
      this.$http({
        url: this.$http.adornUrl('/practice/algorithm/saved-codes'),
        method: 'get',
        params: this.$http.adornParams({ quizId }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.savedCodes = data.data || []
        }
      })
    },
    
    // 加载代码到编辑器
    loadCode(code) {
      this.code = code.codeContent
      this.showLoadDialog = false
      this.$message.success('代码已加载')
    },
    
    // 代码变化
    onCodeChange() {
      this.submitResult = null
    },
    
    // 运行代码
    async runCode() {
      if (!this.code.trim()) {
        this.$message.warning('请输入代码');
        return;
      }
      this.runResult = '';
      try {
        const res = await this.$http.post(this.$http.adornUrl('/practice/algorithm/run'), {
          code: this.code,
          pythonVersion: this.pythonVersion
        });
        console.log('runCode response:', res.data);
        if (res.data && res.data.code === 0 && res.data.result !== undefined) {
          this.runResult = res.data.result || '（无输出）';
        } else {
          this.runResult = res.data.msg || '运行失败';
        }
      } catch (e) {
        this.runResult = '请求失败';
      }
    },
    
    // 工具方法
    getDifficultyType(level) {
      if (level === 1) return 'success'
      if (level === 2) return 'warning'
      if (level === 3) return 'danger'
      return ''
    },
    
    getDifficultyText(level) {
      if (level === 1) return '简单'
      if (level === 2) return '中等'
      if (level === 3) return '困难'
      return '未知'
    },
    
    getResultTitle() {
      if (!this.submitResult) return ''
      if (this.submitResult.status === 1) return '全部通过'
      if (this.submitResult.status === 4) return '部分通过'
      if (this.submitResult.status === 3) return '运行错误'
      return '提交结果'
    },
    
    getResultType() {
      if (!this.submitResult) return 'info'
      if (this.submitResult.status === 1) return 'success'
      if (this.submitResult.status === 4) return 'warning'
      if (this.submitResult.status === 3) return 'error'
      return 'info'
    },
    
    getResultDescription() {
      if (!this.submitResult) return ''
      if (this.submitResult.status === 1) return '恭喜，所有测试用例通过！'
      if (this.submitResult.status === 4) return '部分测试用例未通过，请检查代码。'
      if (this.submitResult.status === 3) return this.submitResult.errorMessage || '运行错误'
      return ''
    },
    
    formatTime(time) {
      if (!time) return ''
      return new Date(time).toLocaleString()
    }
  }
}
</script>

<style scoped>
.algorithm-practice {
  padding: 20px;
}

.quiz-item {
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.3s;
}

.quiz-item:hover {
  background-color: #f5f7fa;
}

.quiz-item.active {
  background-color: #409eff;
  color: white;
}

.quiz-title {
  font-weight: bold;
  margin-bottom: 5px;
}

.quiz-difficulty {
  text-align: right;
}

.no-quiz, .no-selection {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}

.quiz-description {
  margin-bottom: 20px;
}

.quiz-description h3 {
  margin: 15px 0 10px 0;
  color: #303133;
}

.quiz-description p {
  line-height: 1.6;
  color: #606266;
}

.function-signature {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  white-space: pre-wrap;
  margin: 10px 0;
}

.code-editor {
  margin-top: 20px;
}

.editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin-bottom: 15px;
}

.code-textarea {
  width: 100%;
  min-height: 300px;
  padding: 15px;
  border: none;
  outline: none;
  font-family: 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.5;
  resize: vertical;
}

.editor-actions {
  text-align: right;
}

.submit-result {
  margin-top: 20px;
}

.test-case-results {
  margin-top: 15px;
}

.test-case-results h4 {
  margin: 15px 0 10px 0;
  color: #303133;
}

.saved-code-item {
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.3s;
}

.saved-code-item:hover {
  background-color: #f5f7fa;
}

.code-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.code-time {
  font-size: 12px;
  color: #909399;
}

.no-saved-codes {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}
</style>
